// ======================================================================
// Hell Lua Bus ( Lua Bind) Lib
// 
// Copyright 2013 Hell-Prototypes
//
// http://code.google.com/p/hell-prototypes/
//
// This is free software, licensed under the terms of the GNU General
// Public License as published by the Free Software Foundation.
// ======================================================================

#include <usb.h> /* libusb header */
//#include <unistd.h> /* for geteuid */
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

#include "define.h"

static int l_spi_init(lua_State *L)
{
	int mode = get_int_value(L);

    if(mode < 0) {
        lua_pushnumber (L, mode);
        return 1;
    }
    if(mode) {
		mode = 1;
	}

    if(g_usb_dev != NULL) {
        if( usb_control_msg(g_usb_dev, 0x40, USB_SPI_INIT, mode, 0x0000,
                            NULL, 0, 100) < 0) {
            lua_pushnumber (L, -ERR_CTRL_MSG);
        } else {
            lua_pushnumber (L, NO_ERR);
        }
    } else {
        lua_pushnumber (L, -ERR_NO_OPEN);
    }
    return 1;
}

static int l_spi_byte_rw(lua_State *L)
{
	unsigned char buffer[8];

    int value = get_int_value(L);

    if(value < 0) {
        lua_pushnumber (L, value);
        return 1;
    }

    if(g_usb_dev != NULL) {
        if(	usb_control_msg(g_usb_dev, 0x40 | 0x80, USB_SPI_PLAY_1BYTE, value, 0x0000,
                                (char *)buffer, 1, 1000 ) < 0) {
            lua_pushnumber (L, -ERR_CTRL_MSG);
        } else {
            lua_pushnumber (L, buffer[0]);
        }
    } else {
        lua_pushnumber (L, -ERR_NO_OPEN);
    }

    return 1;
}
